<?php

namespace App\Kuafu\Invoice\Controller\Pos;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Invoice\Enum\InvoiceCodeEnum;
use App\Kuafu\Invoice\Service\InvoiceService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Service\OrderInvoiceService;
use Illuminate\Http\Request;
use function Symfony\Component\String\s;

class InvoiceController extends BaseController
{

    /**
     * 开票
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Invoice\Exceptions\InvoiceException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function applyInvoice(Request $request)
    {
        $orderId   = $request->orderId ?? '';
        $shopId    = $request->shopId ?? '';
        $orderType = $request->orderType ?? '';
        return $this->success(OrderInvoiceService::genInvoiceInfo($orderId, $shopId, $orderType));
    }


    /**
     * 取消开票
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Invoice\Exceptions\InvoiceException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function redInvoice(Request $request)
    {
        if (config('app.env') == 'dev' || config('app.env') == 'qa') {
            return $this->fail(InvoiceCodeEnum::ERR_CAN_NOT_USE_QA);
        }
        $orderId    = $request->orderId ?? '';
        $shopId     = $this->shopId;
        $newInvoice = OrderInvoiceService::getInvoiceInfoById($orderId, $shopId);

        if (empty($newInvoice)) {
            return $this->fail(InvoiceCodeEnum::ERR_CANCEL);
        }

        // 获取订单详情
        $orderInfo = OrderInvoiceService::getOrderInfo($newInvoice->orderId, $newInvoice->shopId,
            $newInvoice->orderType);

        if (!empty($orderInfo) && !empty($orderInfo['invoiceInfo']) && $orderInfo['invoiceInfo']['invoiceCanCancelCount'] > 0) {
            // 判断 如果 已经取消了 1 次了, 更新主订单的状态
            $operateSource = CodeEnum::ORDER_OUT_INVOICE_SOURCE_NORMAL;
            $invoiceResult = InvoiceService::redInvoiceOrder($newInvoice->shopId, $newInvoice->orderId, $operateSource);

            if ($invoiceResult['recallStatus']) {

                OrderInvoiceService::reduceOrderInvoiceCount($newInvoice->orderId, $newInvoice->shopId,
                    $newInvoice->orderType);

                OrderInvoiceService::InvoiceStatusUpdate($newInvoice->orderId,
                    $newInvoice->shopId, $newInvoice->orderType, CodeEnum::ORDER_INVOICE_STATUS_CANCELED);
            }
            return $this->success();
        }
        return $this->fail(InvoiceCodeEnum::ERR_CANCEL);
    }
}
